//
//  ViewController.m
//  xxteaDecipher
//
//  Created by 阿凡树 on 2017/9/4.
//  Copyright © 2017年 ManGang. All rights reserved.
//

#import "ViewController.h"
#import "XXTEA.h"
@interface NSAlert (error)
+ (void)alertWithErrorMessage:(NSString*)message;
@end
@implementation NSAlert (error)
+ (void)alertWithErrorMessage:(NSString*)message {
    NSAlert* alert = [[NSAlert alloc] init];
    alert.messageText = message;
    [alert addButtonWithTitle:@"OK"];
    [alert runModal];
}
@end
typedef NS_ENUM(NSInteger,TextFieldType) {
    TextFieldTypeInput  = 1,
    TextFieldTypeOutput  = 2,
};
@interface ViewController ()<NSOpenSavePanelDelegate>
@property (strong) IBOutlet NSTextField *signTextField;
@property (strong) IBOutlet NSTextField *keyTextField;
@property (strong) IBOutlet NSTextField *inputTextField;
@property (strong) IBOutlet NSTextField *outputTextField;
@property (strong) NSOpenPanel *openPanel;
@property (strong) NSURL * selectedPath;
@property (strong) IBOutlet NSTextView *logTextView;
@end
@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _openPanel = [[NSOpenPanel alloc] init];
    _openPanel.canChooseFiles = true;
    _openPanel.canChooseDirectories = true;
    _openPanel.delegate = self;
    _openPanel.canCreateDirectories = true;
    _openPanel.allowedFileTypes = @[@"png",@"plist",@"jpg",@"jpeg"];
}

#pragma mark - Button Action
- (IBAction)selectPath:(NSButton *)sender {
    NSTextField* textField = _inputTextField;
    switch (sender.tag) {
        case TextFieldTypeInput:
            textField = _inputTextField;
            break;
        case TextFieldTypeOutput:
            textField = _outputTextField;
            break;
        default:
            break;
    }
    if (textField.stringValue.length != 0) {
        _openPanel.directoryURL = [NSURL URLWithString:textField.stringValue].URLByDeletingLastPathComponent;
    }
    __weak typeof(self) weakSelf = self;
    [_openPanel beginSheetModalForWindow:[NSApplication sharedApplication].windows[0] completionHandler:^(NSInteger result) {
        if (result == NSModalResponseOK) {
            textField.stringValue = weakSelf.selectedPath.path;
        }
    }];
}

- (IBAction)startdecypher:(NSButton *)sender {
    if (![self checkPathIsDirectory:_inputTextField.stringValue]) {
        return;
    }
    if (![self checkPathIsDirectory:_outputTextField.stringValue]) {
        return;
    }
    sender.enabled = NO;
    [self circleFind:_inputTextField.stringValue andOutPutPath:_outputTextField.stringValue];
    sender.enabled = YES;
    [self addLogToTextView:@"代码解密全部完成。Author:afantree(www.52pojie.cn)"];
}

#pragma mark - Private

- (BOOL)checkPathIsDirectory:(NSString *)path {
    BOOL isDirectory = NO;
    if (![[NSFileManager defaultManager] fileExistsAtPath:_outputTextField.stringValue isDirectory:&isDirectory]) {
        [NSAlert alertWithErrorMessage:@"目录/路径有错"];
        return NO;
    }
    if (!isDirectory) {
        [NSAlert alertWithErrorMessage:@"目录/路径请选择文件夹"];
        return NO;
    }
    return YES;
}

- (void)addLogToTextView:(NSString *)msg {
    self.logTextView.string = [NSString stringWithFormat:@"%@\n%@",self.logTextView.string,msg];
    [self.logTextView scrollRangeToVisible: NSMakeRange(self.logTextView.string.length, 0)];
}

- (void)circleFind:(NSString *)path andOutPutPath:(NSString *)outputPath {
    NSError* error = nil;
    NSArray* pathArray = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:path error:&error];
    if (error) {
        NSLog(@"error = %@",error);
        return;
    }
    for (NSString* item in pathArray) {
        if ([item isEqualToString:@".DS_Store"]) {
            continue;
        }
        BOOL isDirectory = NO;
        NSString* filename = [NSString stringWithFormat:@"%@/%@",path,item];
        NSString* outputFilename = [NSString stringWithFormat:@"%@/%@",outputPath,item];
        [[NSFileManager defaultManager] fileExistsAtPath:filename isDirectory:&isDirectory];
        if (isDirectory) {
            if (![[NSFileManager defaultManager] fileExistsAtPath:outputFilename]) {
                [[NSFileManager defaultManager] createDirectoryAtPath:outputFilename withIntermediateDirectories:YES attributes:nil error:nil];
            }
            [self circleFind:filename andOutPutPath:outputFilename];
        }
        if ([item hasSuffix:@".luac"]) {
            [self addLogToTextView:[NSString stringWithFormat:@"准备解密:%@",filename]];
            NSData* fileData = [NSData dataWithContentsOfFile:filename];
            NSInteger signLength = _signTextField.stringValue.length;
            NSData* originData = [fileData subdataWithRange:NSMakeRange(signLength, fileData.length - signLength)];
            //aaaaaaaaaaaaaaaaa socrazy123key860412
            NSData* decryptData = [XXTEA decrypt:originData stringKey:_keyTextField.stringValue];
            NSString* decryptName = [outputFilename stringByReplacingOccurrencesOfString:@".luac" withString:@".lua"];
            [decryptData writeToFile:decryptName atomically:YES];
            [self addLogToTextView:[NSString stringWithFormat:@"输出完成 ---->  %@",decryptName]];
        }
        //NSLog(@"item = %@",filename);
    }
}

#pragma mark - NSOpenSavePanelDelegate

- (void)panelSelectionDidChange:(NSOpenPanel*)sender {
    _selectedPath = sender.URL;
    NSLog(@"sender.URL = %@",sender.URL);
}

@end
